package com.corpgovernment.organization.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.organization.enums.CardTypeEnum;
import com.corpgovernment.api.organization.vo.TransferEmployeeOrgInfoVo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.organization.constant.FreshPassengerConst;
import com.corpgovernment.organization.entity.db.MbFreshPassenger;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgNonEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.mapper.MbFreshPassengerMapper;
import com.corpgovernment.organization.service.*;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.corpgovernment.common.enums.SystemType.zhongjin;

/**
 * 员工非员工新鲜度service实现
 *
 * @author wangyujue
 */
@Service
@Slf4j
public class FreshPassengerServiceImpl extends OrganizationBaseService implements IFreshPassengerService {

	@Autowired
	private MbFreshPassengerMapper freshPassengerMapper;
	@Autowired
	private OrganizationApollo organizationApollo;
	@Autowired
	private IOrganizationEmployeeService organizationEmployeeService;
	@Autowired
	private IOrganizationNonEmployeeService organizationNonEmployeeService;
	@Autowired
	private IOrgUserIdCardService orgUserIdCardService;

	@Override
	public boolean save(MbFreshPassenger mbFreshPassenger) {
		int i = freshPassengerMapper.insertSelective(mbFreshPassenger);
//        insertOperateLog(mbFreshPassenger);
		return i > 0;
	}

	@Override
	public boolean fresh(List<MbFreshPassenger> mbFreshPassengers) {
		List<String> employeeUids = mbFreshPassengers.stream()
				.filter(p -> StringUtils.isNotBlank(p.getEmployeeUid()))
				.map(MbFreshPassenger::getEmployeeUid)
				.collect(Collectors.toList());

		List<Long> nonEmployeeUids = mbFreshPassengers.stream()
				.filter(p -> p.getNonEmployeeUid() != null)
				.map(MbFreshPassenger::getNonEmployeeUid)
				.collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(employeeUids)) {
			freshPassengerMapper.freshEmployee(employeeUids);
		}
		if (CollectionUtils.isNotEmpty(nonEmployeeUids)) {
			freshPassengerMapper.freshNonEmployee(nonEmployeeUids);
		}
		return true;
	}

    @Override
    public boolean updateEmployeeOrg(MbFreshPassenger mbFreshPassenger) {
		int i = freshPassengerMapper.updateEmployeeOrg(mbFreshPassenger);
        return i > 0;
    }

    @Override
    public boolean batchUpdateEmployeeOrg(List<String> uids, String orgId) {
		int i = freshPassengerMapper.batchUpdateEmployeeOrg(uids, orgId);
        return i > 0;
    }

    @Override
    public boolean deleteEmployee(String uid, String orgId) {
//        deleteOperateLog(uid);
		int i = freshPassengerMapper.deleteEmployee(uid, orgId);
        return i > 0;
    }

    @Override
    @Transactional
    public boolean deleteNonEmployee(Long nonEmployeeUid) {
//        deleteOperateLog(String.valueOf(nonEmployeeUid));
		int i = freshPassengerMapper.deleteNonEmployee(nonEmployeeUid);
        return i > 0;
    }

    @Override
    public boolean batchSave(List<MbFreshPassenger> needSaveFreshPassengerList) {
		int i = freshPassengerMapper.batchSave(needSaveFreshPassengerList);
//        needSaveFreshPassengerList.forEach(e -> {
//            insertOperateLog(e);
//        });
        return i > 0;
    }

    @Override
    public List<MbFreshPassenger> listByOrgId(String orgId, String uid, Integer pageNum, List<String> uids, List<Long> noEmployeeIds, Integer pageSize) {
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgId(orgId, uid, uids, noEmployeeIds);
    }

    @Override
    public List<MbFreshPassenger> listByOrgIds(List<String> orgIds, String uid, List<String> uids,
                                               List<Long> noEmployeeIds, String currentUserOrgId,
                                               Integer pageNum, Integer pageSize) {
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgIds(orgIds, uid, uids, noEmployeeIds, currentUserOrgId);
    }

    @Override
    public List<MbFreshPassenger> listByOrgIdsAndUid(List<String> bookRangeOrgIds, String currentUid, List<String> excludeUids,
                                                     List<Long> excludeNoEmpIds, String currentUserOrgId, Integer pageNum, Integer pageSize) {
        if (bookRangeOrgIds == null) {
            bookRangeOrgIds = Collections.emptyList();
        }
        if (excludeUids == null) {
            excludeUids = Collections.emptyList();
        }
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgIdsAndUid(bookRangeOrgIds, currentUid, excludeUids, excludeNoEmpIds, currentUserOrgId);
    }

    @Override
    public List<MbFreshPassenger> listByOrgIdAndName(String orgId, String uid, String query, Integer pageNum, List<String> uids, List<Long> noEmployeeIds, Integer pageSize) {
		List<Long> freshPassengerIds = new ArrayList<>();
		if (StringUtils.isNotBlank(query)) {
			freshPassengerIds = this.queryLikeName(query);
		}
		if (CollectionUtils.isEmpty(freshPassengerIds)) {
			return new ArrayList<>();
		}
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgIdAndName(orgId, uid, freshPassengerIds, uids, noEmployeeIds);
	}

	@Override
	public List<MbFreshPassenger> listByOrgIdsAndUidAndName(List<String> orgIds, String uid, String query,
															List<String> uids, List<Long> noEmployeeIds,
															String currentUserOrgId, Integer pageNum, Integer pageSize) {
		if (orgIds == null) {
			orgIds = Collections.emptyList();
		}
		if (uids == null) {
			uids = Collections.emptyList();
		}
		List<Long> freshPassengerIds = new ArrayList<>();
		if (StringUtils.isNotBlank(query)) {
			String systemType = organizationApollo.getSystemType();
			if (Objects.equals(zhongjin.getCode(), systemType)) {
				// 名称精确匹配或身份证号精确匹配
				freshPassengerIds = this.queryByNameOrCardNo(query);
			} else {
				// 名称模糊查询
				freshPassengerIds = this.queryLikeName(query);
			}
		}
		if (CollectionUtils.isEmpty(freshPassengerIds)) {
			return new ArrayList<>();
		}
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgIdsAndUidAndName(orgIds, uid, freshPassengerIds, uids, noEmployeeIds, currentUserOrgId);
	}

	/**
	 * 根据名称或身份证号精确查询
	 *
	 * @param query
	 * @return
	 */
	private List<Long> queryByNameOrCardNo(String query) {
		List<Long> freshPassengerIds = new ArrayList<>();
		// 名称精确匹配或身份证号精确匹配
		List<MbOrgEmployeeInfo> orgEmployeeInfoList = organizationEmployeeService.findByName(query);
		List<MbOrgNonEmployeeInfo> orgNonEmployeeInfoList = organizationNonEmployeeService.findByName(query);
		List<MbOrgUserIdcard> orgUserIdcardList = orgUserIdCardService.findByTypeAndNo(CardTypeEnum.ID_CARD.getCode(), query);
		List<String> employeeIds = new ArrayList<>();
		employeeIds.addAll(orgEmployeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList()));
		employeeIds.addAll(orgUserIdcardList.stream().map(MbOrgUserIdcard::getEmployeeUid).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
		List<Long> nonEmployeeIds = new ArrayList<>();
		nonEmployeeIds.addAll(orgNonEmployeeInfoList.stream().map(MbOrgNonEmployeeInfo::getId).collect(Collectors.toList()));
		nonEmployeeIds.addAll(orgUserIdcardList.stream().map(MbOrgUserIdcard::getNonEmployeeId).filter(Objects::nonNull).collect(Collectors.toList()));
		if (!CollectionUtils.isEmpty(employeeIds) || !CollectionUtils.isEmpty(nonEmployeeIds)) {
			freshPassengerIds = this.queryByUserIds(employeeIds, nonEmployeeIds);
		}
		return freshPassengerIds;
	}

	/**
	 * 根据员工id和非员工id查询
	 *
	 * @param employeeIds
	 * @param nonEmployeeIds
	 * @return
	 */
	private List<Long> queryByUserIds(List<String> employeeIds, List<Long> nonEmployeeIds) {
		List<Long> freshPassengerIds = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(employeeIds)) {
			List<MbFreshPassenger> employeeList = freshPassengerMapper.findByEmployeeIds(employeeIds);
			freshPassengerIds.addAll(employeeList.stream().map(MbFreshPassenger::getId).distinct().collect(Collectors.toList()));
		}
		if (CollectionUtils.isNotEmpty(nonEmployeeIds)) {
			List<MbFreshPassenger> nonEmployeeList = freshPassengerMapper.findByNonEmployeeIds(nonEmployeeIds);
			freshPassengerIds.addAll(nonEmployeeList.stream().map(MbFreshPassenger::getId).distinct().collect(Collectors.toList()));
		}
		return freshPassengerIds;
	}

	@Override
	public List<MbFreshPassenger> listByOrgIdsAndName(List<String> orgIds, String uid, String query, List<String> uids, List<Long> noEmployeeIds, String currentUserOrgId, Integer pageNum, Integer pageSize) {
		List<Long> freshPassengerIds = new ArrayList<>();
		if (StringUtils.isNotBlank(query)) {
			String systemType = organizationApollo.getSystemType();
			if (Objects.equals(zhongjin.getCode(), systemType)) {
				// 名称精确匹配或身份证号精确匹配
				freshPassengerIds = this.queryByNameOrCardNo(query);
			} else {
				// 名称模糊查询
				freshPassengerIds = this.queryLikeName(query);
			}
		}
		if (CollectionUtils.isEmpty(freshPassengerIds)) {
			return new ArrayList<>();
		}
		PageContext.startPage(pageNum, pageSize);
		return freshPassengerMapper.listByOrgIdsAndName(orgIds, uid, freshPassengerIds, uids, noEmployeeIds, currentUserOrgId);
	}

    @Override
    public boolean updateByEmployeeId(MbFreshPassenger mbFreshPassenger) {
	    if (StringUtils.isBlank(mbFreshPassenger.getEmployeeUid())){
	        return false;
        }
        Example example = new Example(MbFreshPassenger.class);
        example.createCriteria().andEqualTo(FreshPassengerConst.EMPLOYEE_UID, mbFreshPassenger.getEmployeeUid()).andEqualTo("isDeleted", false);
        try {
			MbFreshPassenger oldValue = freshPassengerMapper.selectOneByExample(example);
//            updateOperateLog(oldValue, mbFreshPassenger);
        } catch (Exception e) {
            log.error("更新操作获取oldValue失败，FreshPassengerServiceImpl.updateByEmployeeId");
        }
		int i = freshPassengerMapper.updateByExampleSelective(mbFreshPassenger, example);
        return i > 0;
    }

    @Override
    public boolean updateByNonEmployeeId(MbFreshPassenger mbFreshPassenger) {
	    if (Objects.isNull(mbFreshPassenger.getNonEmployeeUid())){
	        return false;
        }
        Example example = new Example(MbFreshPassenger.class);
        example.createCriteria().andEqualTo(FreshPassengerConst.NON_EMPLOYEE_UID, mbFreshPassenger.getNonEmployeeUid()).andEqualTo("isDeleted", false);
		MbFreshPassenger oldValue = freshPassengerMapper.selectOneByExample(example);
//        updateOperateLog(oldValue, mbFreshPassenger);
		int i = freshPassengerMapper.updateByExampleSelective(mbFreshPassenger, example);
        return i > 0;
    }

	@Override
	public List<MbFreshPassenger> listNonEmployeeByUid(String uid, String orgId, List<Long> noEmployeeIds, List<String> uids, String name, Integer pageSize, Integer pageNum) {
		PageContext.startPage(pageNum, pageSize);
		List<Long> freshPassengerIds = new ArrayList<>();
		if (StringUtils.isNotBlank(name)) {
			freshPassengerIds = this.queryLikeName(name);
		}
		return freshPassengerMapper.listNonEmployeeByUid(uid, orgId, noEmployeeIds, uids, freshPassengerIds);
	}

	public List<Long> queryLikeName(String name) {
		List<MbFreshPassenger> freshPassengerList = freshPassengerMapper.queryAllName();
		return freshPassengerList.stream().filter(e -> StringUtils.contains(e.getName(), name) || StringUtils.contains(e.getEnName(), name)).map(MbFreshPassenger::getId).collect(Collectors.toList());
	}

	@Override
	public boolean batchInvalid(List<String> uids, String orgId) {
		if (CollUtil.isEmpty(uids) || StrUtil.isBlank(orgId)) {
			return false;
		}
		return freshPassengerMapper.batchUpdateValid(uids, orgId, 1) > 0;
	}

	@Override
    public boolean batchValid(List<String> uids, String orgId) {
        if (CollUtil.isEmpty(uids) || StrUtil.isBlank(orgId)) {
            return false;
        }
		return freshPassengerMapper.batchUpdateValid(uids, orgId, 0) > 0;
    }

	@Override
	public boolean deleteNonEmployeeByUid(String uid) {
		return freshPassengerMapper.deleteNonEmployeeByUid(uid) > 0;
	}

	@Override
	public boolean updateAccountValid(String uid, Integer accountValid) {
		return freshPassengerMapper.updateAccountValid(uid, accountValid) > 0;
	}

	@Override
	public int updateByRecord(MbFreshPassenger record) {
		Example example = new Example(MbFreshPassenger.class);
		example.createCriteria()
			   .andEqualTo("employeeUid", record.getEmployeeUid())
			   .andEqualTo("orgId", record.getOrgId())
			   .andEqualTo("isDeleted", true);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(mbFreshPassengers)){
			return 0;
		}
		MbFreshPassenger mbFreshPassenger = mbFreshPassengers.get(0);
		mbFreshPassenger.setIsDeleted(false);
		return freshPassengerMapper.updateByPrimaryKeySelective(mbFreshPassenger);
	}

	@Override
	public Boolean batchUpdateFreshPassenger(TransferEmployeeOrgInfoVo request) {
		request.getEmployeeOrgInfoList().forEach(item ->{
			Example example = new Example(MbFreshPassenger.class);
			example.createCriteria().andEqualTo("employeeUid", item.getUid()).andEqualTo("orgId", item.getOldOrgId());

			MbFreshPassenger freshPassenger = new MbFreshPassenger();
			freshPassenger.setOrgId(request.getNewOrgId());
			freshPassengerMapper.updateByExampleSelective(freshPassenger, example);
		});
		return true;
	}

	@Override
	public boolean deleteByUidAndOrgId(List<MbFreshPassenger> mbFreshPassengerList) {
		if (CollectionUtils.isEmpty(mbFreshPassengerList)){
			return false;
		}
		return freshPassengerMapper.deleteByUidAndOrgId(mbFreshPassengerList) > 0;
	}

	@Override
	public boolean insertList(List<MbFreshPassenger> mbFreshPassengerList) {
		if (CollectionUtils.isEmpty(mbFreshPassengerList)){
			return false;
		}
		return freshPassengerMapper.insertList(mbFreshPassengerList) > 0;
	}

	@Override
	public boolean updateALLByRecord(MbFreshPassenger record) {
		Example example = new Example(MbFreshPassenger.class);
		example.createCriteria()
				.andEqualTo("employeeUid", record.getEmployeeUid())
				.andEqualTo("orgId", record.getOrgId())
				.andEqualTo("isDeleted", true);
		return freshPassengerMapper.updateByExampleSelective(record, example) > 0;
	}
}
